package model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**.
 * Class use to save and load
 * @author jaubertbenjamin
 *
 */
public final class Storage {

     /**.
     * for json
     */
    private static ObjectMapper mapper;

    /**.
     * for xml
     */
    private static XStream xstream;

    /**.
     * default constructor
     */
    private Storage() {

    }

     /**.
     * Save a json file
     * @param list movies list
     * @param path location of the file
     */
    public static final void jsonSerialization(final MoviesList list, final String path){
        mapper = new ObjectMapper();
        try {
           mapper.writeValue(new File(path), list);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

     /**.
      * Load a json file
      * @param path the location of the file
      * @return the movies list
      */
    public static final MoviesList jsonDeserialization(final String path) {
        MoviesList list = null;
        mapper = new ObjectMapper();
        try {
           list = mapper.readValue(new File(path), MoviesList.class);
        } catch (JsonParseException e) {
           e.printStackTrace();
        } catch (JsonMappingException e) {
           e.printStackTrace();
        } catch (IOException e) {
           e.printStackTrace();
        }
        return list;
    }

    /**.
     * Save a xml file
     * @param list list of movies
     * @param path location of the file
     */
    public static final void xmlSerialization(final MoviesList list, final String path){
        xstream = new XStream(new DomDriver());
        try {
            xstream.toXML(list, new FileOutputStream(path));
        } catch (FileNotFoundException e) {
                e.printStackTrace();
        }
    }

    /**.
     * load a xml file
     * @param path location of the file
     * @return the movies list
     */
    public static final MoviesList xmlDeserialization(final String path) {
        xstream = new XStream(new DomDriver());
        MoviesList list = null;
        try {
            list = (MoviesList) xstream.fromXML(new FileInputStream(new File(path)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }
}
